﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SqliteORM;

namespace ChgDoc.Entity
{
    public enum PageRender
    {
        Template = 0,
        Redirect = 1,
        TemplateData = 2,
        FileResponse = 3,
        TemplateSql = 5
    }

	public class PageResponseSpecialNames
	{
		public const string Homepage = ".homepage";
		public const string FourOhFour = ".404";

		public static bool IsSpecial(string name)
		{
			return (name != null && name.Length > 1 && name[ 0 ] == '.');
		}
	}

	[Table]
	public class PageResponse : TableBase<PageResponse>
	{
		private string _url;
		public const string UrlValidCharacters = "abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ0123456789_-=+#.";

		[PrimaryKey( true )]
		public long Id { get; set; }

		[Field(IsCaseInsensitive = true)]
		public string Url
		{
			get { return _url; } 
			set
			{
			    if (IsValidUrl(value))	
				    _url = value;
			}
		}

        public static bool IsValidUrl(string url)
        {
            if (url == null)
                return false;

            if (!PageResponseSpecialNames.IsSpecial(url))
                foreach (char c in url)
                    if (UrlValidCharacters.IndexOf(c) == -1)
                        return false;
            
            return true;
	    }

		[Field]
		public PageRender Render { get; set; }

		[Field]
		public string RenderOptions { get; set; }
		

		public static PageResponse Read(long id)
		{
			return Get( ad => ad.Read( id ) );
		}

        public static PageResponse Read(string url)
        {
            if (string.IsNullOrEmpty(url))
                return null;
			
        	return Config.Log.LogResultInfo( ( ) => Get( ad => ad.Select().Where( t => t.Url == url ).FirstOrDefault() ) );
        }

		public static void Delete(long id)
		{
			Do( ad => ad.Delete( id ) );
		}

		public static List<PageResponse> ReadAll( )
		{
			return Get( ad => ad.Select().ToList() );
		}

		public override string ToString( )
		{
			return "PageResponse: " +_url;
		}
	}
}
